package scopes

import (
	"strconv"

	"github.com/goravel/framework/contracts/database/orm"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
)

func Paginator(page string, limit string) func(methods orm.Query) orm.Query {
	return func(query orm.Query) orm.Query {
		page, _ := strconv.Atoi(page)
		limit, _ := strconv.Atoi(limit)
		offset := (page - 1) * limit

		return query.Offset(offset).Limit(limit)
	}
}

func tenantQuery(ctx http.Context) func(methods orm.Query) orm.Query {
	return func(query orm.Query) orm.Query {
		return query
	}

}

func Query(ctx http.Context) orm.Query {
	return facades.Orm().Query()
}

func Create(ctx http.Context, model any) error {
	//tenantID, ok := ctx.Value("tenant_id").(uint)
	//if !ok {
	//	return fmt.Errorf("failed to get tenant_id from context")
	//}
	//
	//// 使用反射设置 TenantID 字段
	//modelValue := reflect.ValueOf(model)
	//if modelValue.Kind() == reflect.Ptr {
	//	modelValue = modelValue.Elem()
	//}
	//
	//tenantIDField := modelValue.FieldByName("TenantID")
	//if tenantIDField.IsValid() && tenantIDField.CanSet() {
	//	tenantIDField.SetUint(uint64(tenantID))
	//} else {
	//	facades.Log().Error("Failed to set TenantID field")
	//	return fmt.Errorf("failed to set TenantID field")
	//}

	// 创建记录
	if err := facades.Orm().Query().Create(model); err != nil {
		facades.Log().Error("Failed to create model: ", err)
		return err
	}

	return nil
}
